require('dotenv').config()
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const routes = require('./routes')
const path = require('path')
const mysql = require('mysql2/promise')

class Server {
  constructor() {
    this.app = express()
    this.conf = {
      serverPort: process.env.SERVER_PORT || 37654,
      serverName: process.env.SERVER_NAME || 'Node_Poster',
      dbHost: process.env.DB_HOST || 'localhost',
      dbName: process.env.DB_NAME || 'node_poster',
      dbUser: process.env.DB_USER || 'root',
      dbPass: process.env.DB_PASS || 'rootpass'
    }

    this.configureMiddleware()
    this.configureViews()
    this.configureRoutes()
    this.configureStatic()

    // 不需要数据库的话，可以注释掉这一行
    // this.createMySQLConnectionPool()
  }

  configureMiddleware() {
    this.app.use(bodyParser.json())
    this.app.use(bodyParser.urlencoded({ extended: true }))
    this.app.use(cors())
  }

  configureViews() {
    this.app.set('view engine', 'pug')
    this.app.set('views', path.join(__dirname, 'views'))
  }

  configureRoutes() {
    this.app.use('/', routes(this))
  }

  configureStatic() {
    this.app.use('/public', express.static(path.join(__dirname, 'public')))
  }

  async createMySQLConnectionPool() {
    this.pool = mysql.createPool({
      host: this.conf.dbHost,
      user: this.conf.dbUser,
      password: this.conf.dbPass,
      database: this.conf.dbName,
    })

    try {
      // 尝试获取一个连接并执行简单查询以测试连接
      const connection = await this.pool.getConnection()
      await connection.query('SELECT 1')
      connection.release()
      console.log('MySQL connection pool created successfully.')
    } catch (err) {
      console.error('Error creating MySQL connection pool:', err)
    }
  }

  async fetchData(sql) {
    try {
      const connection = await this.pool.getConnection();
      const [rows] = await connection.query(sql);
      connection.release();
      return rows;
    } catch (err) {
      console.error(err);
    }
  }

  start() {
    this.app.listen(this.conf.serverPort, () => {
      console.log(
        `${this.conf.serverName} listening on port ${this.conf.serverPort}`
      )
    })
  }
}

const server = new Server()
server.start()
